import 'package:inmotion_pro/l10n/local.dart';
import 'package:inmotion_pro/pages/mixin/vehicle_type_mixin.dart';
import 'package:inmotion_pro/routes/app_routes.dart';
import 'package:ble_helper_plugin/library.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:lx_widgets_library/lx_widgets_library.dart';
import 'controller.dart';

// 蓝牙连接页面
class BleSearchView extends BaseGetView<BleSearchController>
    with VehicleTypeMixin {
  BleSearchView({super.key});

  @override
  bool? get hideNavShadow => true; // 隐藏导航栏阴影

  @override
  Color? get barBackgroundColor => Colors.black; // 设置导航栏背景颜色为蓝色

  @override
  Widget get backView => IconButton(
        icon: const Icon(
          Icons.close_rounded,
          color: GrayColor.gray5,
        ),
        onPressed: () => Get.back(),
      );

  @override
  Widget buildBody(BuildContext context) {
    // 搜索中底部距离
    final double searchingBottom = CONTENT_MARGIN / 2;
    // 搜索中顶部距离
    final double searchingTop = CONTENT_MARGIN;
    // 搜索中高度
    final double searchingHeight = 30.w + 15.w + CONTENT_MARGIN;
    // 搜索完成高度
    final double searchCompleteHeight = 30.w;
    // 常见问题底部距离
    final double commonProblemBottom = tabBarSpace + 20.w;
    // 常见问题顶部距离
    final double commonProblemTop = CONTENT_MARGIN * 2;
    // 常见问题高度
    final double commonProblemHeight = 20.w;
    // 搜索按钮顶部距离
    final double searchBtnTop = 30.w;
    // 搜索按钮高度
    final double searchBtnHeight = 45.w;

    // 主体页面
    return Container(
      color: Colors.black,
      height: double.infinity,
      width: double.infinity,
      child: Stack(
        alignment: Alignment.topCenter,
        children: [
          Obx(() {
            final allTopHeight = appBarHeight +
                (controller.state.bluetoothConnectState.value ==
                        CustomBluetoothConnectState.isScanning
                    ? searchingTop + searchingHeight + searchingBottom
                    : searchingTop + searchCompleteHeight + searchingBottom);
            final allBottomHeight = commonProblemBottom +
                commonProblemHeight +
                commonProblemTop +
                (controller.state.bluetoothConnectState.value ==
                        CustomBluetoothConnectState.isScanning
                    ? 0
                    : searchBtnTop + searchBtnHeight);
            return Column(
              children: [
                _buildSearchingView(
                  context,
                  searchingTop,
                  searchingBottom,
                  searchingHeight,
                  searchCompleteHeight,
                ),
                SizedBox(
                  height: screenHeight - allTopHeight - allBottomHeight,
                  child: _buildListView(),
                )
              ],
            );
          }),

          // 底部组件
          Positioned(
            bottom: commonProblemBottom,
            left: CONTENT_MARGIN,
            right: CONTENT_MARGIN,
            child: Column(
              children: [
                // 重新搜索按钮
                _buildSearchAgainButton(searchBtnTop, searchBtnHeight),

                // 常见问题
                _buildCommonProblem(
                    context, commonProblemTop, commonProblemHeight),
              ],
            ),
          ),
        ],
      ),
    );
  }

  // 搜索结果
  _buildListView() {
    return EmptyOrLoading(
      emptyMessage: local.no_data_available,
      isLoading: controller.state.scanResults.value == null,
      isEmpty: controller.state.scanResults.value != null &&
          controller.state.scanResults.value!.isEmpty,
      child: ListView.builder(
        itemCount: controller.state.scanResults.value?.length ?? 0,
        itemBuilder: (c, index) {
          if (controller.state.scanResults.value == null) return Container();
          CustomScanResult result = controller.state.scanResults.value![index];
          return GestureDetector(
            onTap: () {
              // 点击连接设备
              controller.connectDeviceOnTap(result);
            },
            child: Padding(
              padding: EdgeInsets.all(CONTENT_MARGIN),
              child: ClipRRect(
                borderRadius: BorderRadius.circular(8.w),
                child: Container(
                  constraints: BoxConstraints(
                    minHeight: 80.w,
                  ),
                  padding: EdgeInsets.only(
                    left: CONTENT_MARGIN,
                    right: CONTENT_MARGIN,
                    top: 10.w,
                    bottom: 10.w,
                  ),
                  color: GrayColor.gray1,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      // 设备名称
                      Container(
                        constraints: BoxConstraints(
                          maxWidth: screenWidth -
                              4 * CONTENT_MARGIN -
                              40.w -
                              24 -
                              CONTENT_MARGIN,
                        ),
                        child: LxText(
                          result.device.advName,
                          color: Colors.white,
                          fontWeightEnum: LxFontWeightEnum.titleMedium,
                        ),
                      ),
                      Row(
                        children: [
                          // 信号强度
                          _getSignalImagePath(result.rssi),
                          SizedBox(width: CONTENT_MARGIN),
                          // 设备图标
                          Image.asset(
                            vehicleTypeMixinGetVehicleType(
                              bleName: result.device.advName,
                            ).assetPath,
                            height: 60,
                            fit: BoxFit.fitHeight,
                          ),
                        ],
                      )
                    ],
                  ),
                ),
              ),
            ),
          );
        },
      ),
    );
  }

  // 搜索中 / 搜索完成（轻点连接设备）
  Widget _buildSearchingView(
    BuildContext context,
    double top,
    double bottom,
    double searchingHeight,
    double searchCompleteHeight,
  ) {
    return Visibility(
      visible: controller.state.bluetoothConnectState.value ==
          CustomBluetoothConnectState.isScanning,
      replacement: Padding(
          padding: EdgeInsets.only(
            top: top,
            bottom: bottom,
            left: CONTENT_MARGIN * 2,
          ),
          child: SizedBox(
            height: searchCompleteHeight,
            child: Align(
              alignment: Alignment.centerLeft,
              child: Container(
                constraints: BoxConstraints(
                  maxWidth: screenWidth - CONTENT_MARGIN * 3,
                ),
                // 点击连接设备
                child: DelayedBuildView(
                  delay: Duration(milliseconds: controller.delayTimeToScan + 1),
                  child: LxText(
                    context.s.click_device_to_connect,
                    color: Colors.white.withOpacity(0.6),
                    fontWeightEnum: LxFontWeightEnum.bodyMedium,
                  ),
                ),
              ),
            ),
          )),
      child: Padding(
        padding: EdgeInsets.only(top: top, bottom: bottom),
        child: SizedBox(
          height: searchingHeight,
          child: Column(
            children: [
              // 搜索中提示
              LxText(
                context.s.searching,
                color: Colors.white,
                fontWeightEnum: LxFontWeightEnum.bodyMedium,
              ),
              SizedBox(height: CONTENT_MARGIN),
              // 搜索中loading动画
              Loading.loadingWidget(color: Colors.white),
            ],
          ),
        ),
      ),
    );
  }

  // 重新搜索按钮
  Widget _buildSearchAgainButton(double top, double height) {
    return Obx(
      () => Visibility(
        visible: controller.state.bluetoothConnectState.value !=
            CustomBluetoothConnectState.isScanning,
        child: DelayedBuildView(
          delay: Duration(milliseconds: controller.delayTimeToScan + 1),
          child: Padding(
            padding: EdgeInsets.only(
              top: top,
              left: CONTENT_MARGIN,
              right: CONTENT_MARGIN,
            ),
            child: LxButton(
              borderRadius: BorderRadius.circular(4.w),
              height: height,
              title: controller.state.searchBtnTitle.value,
              onTap: controller.searchAgainOnTap,
              buttonAlignmentEnum: ButtonAlignmentEnum.block,
              fontWeightEnum: LxFontWeightEnum.bodyLarge,
            ),
          ),
        ),
      ),
    );
  }

  // 常见问题
  Widget _buildCommonProblem(BuildContext context, double top, double height) {
    return Padding(
      padding: EdgeInsets.only(top: top),
      child: GestureDetector(
        onTap: () => Get.toNamed(AppRoutes.SEARCH_COMMON_PROBLEM),
        child: Center(
          child: SizedBox(
            height: height,
            child: LxText(
              context.s.common_issues,
              color: Colors.white,
              fontWeightEnum: LxFontWeightEnum.bodyMedium,
            ),
          ),
        ),
      ),
    );
  }

  // 根据蓝牙rssi值获取信号强度图片
  Widget _getSignalImagePath(int? rssi) {
    if (rssi == null) {
      return const Icon(Icons.signal_cellular_alt_1_bar_rounded);
    }
    if (rssi > -80) {
      return const Icon(Icons.signal_cellular_alt_rounded);
    }
    if (rssi > -90) {
      return const Icon(Icons.signal_cellular_alt_2_bar_rounded);
    } else {
      return const Icon(Icons.signal_cellular_alt_1_bar_rounded);
    }
  }
}
